package com.manager.ctroller;

import com.example.utils.Utils;
import com.manager.dao.UserDao;
import org.apache.commons.dbutils.QueryRunner;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

/**
 * @author mucd
 * 2021年06月26日  20:07
 */

@WebServlet(value = "/Insert")
public class Inster extends HttpServlet implements UserDao {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        String setName = req.getParameter("setName");
        String setGender = req.getParameter("setGender");
        String setAge = req.getParameter("setAge");
        String setAddress = req.getParameter("setAddress");
        String setQQ = req.getParameter("setQQ");
        String setEmail = req.getParameter("setEmail");
        if (insert(setName, setGender, setAge, setAddress, setQQ, setEmail) > 0) {

            resp.sendRedirect("limit?page=1");
        }else{
            System.out.println("没有添加");
        }
    }

    /**
     * 添加
     */
    @Override
    public int insert(String name, String gender, String age, String address, String qq, String email) {
        QueryRunner queryRunner = new QueryRunner(Utils.getDataSource());
        try {
            int insert = queryRunner.update(
                    "insert into manager.person (name,gender,age,address,qq,email) values (?,?,?,?,?,?)"
                    , name, gender, age, address, qq, email
            );
            if (insert > 0){
                return insert;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return 0;
    }
}